//app.js
//const AV = require('./utils/av-weapp-min.js')
const util = require('./utils/util.js');
const api = require('./utils/ajax.js')
// LeanCloud 应用的 ID 和 Key
// AV.init({
//   appId: 'wx14f75e07af881579',
//   appKey: 'wA3sIlhOWzVHQubxmJyK2Ef8',
// });
App({
  onLaunch: function () {
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo;
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
  },
  onLoad: function () {
    //进入应用时检查语言设置
    var language = wx.getStorageSync('selectedLanguage');
    if (language) {
      this.globalData.settings.language = language;
    } else {
      //使用系统语言设定 user-info COUNTRY, 暂时默认为中文 
      this.globalData.settings.language = 0;
    }
    //检查EMP ID设置
    var emp = wx.getStorageSync('employeeId')
    if (emp) {
      this.globalData.settings.employeeId = emp
    } else {
      this.globalData.settings.employeeId = null
    }

    //调用API从本地缓存中获取数据
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
  },
  appLogin: function (type) {
    let that = this;
    wx.login({
      success: function (res) {
        let code = res.code;
        if (code) {
          wx.request({
            url: that.globalData.commonUrl + '/account/wx/refreshSessionKey?code='+code,
            method: "post",
            success: function (res) {
              if (res.data.code==200){
                that.getToken(res.data.data.sessionKey, type);
              }else{
                wx.hideLoading();
              }
            },
            fail: function () {
              wx.hideLoading();
            }
          })
        } else {
          wx.hideLoading();
        }

      }
    })
  },
  getToken: function (sessionKey, type){
    let that = this;
    withCredentials: true,
    wx.getUserInfo({
      success: function (res) {
        let codeData = res;
        wx.request({
          url: that.globalData.commonUrl + '/auth/oauth/token?sessionKey=' + sessionKey,
          method: "post",
          success: function (res) {
            if (res.data.code==200) {
              let _token = res.data.data.access_token;
              let token_type = res.data.data.token_type;
              that.globalData.token = token_type+" "+_token;
              that.globalData.userInfo = codeData.userInfo;
              wx.setStorage({
                key: 'userInfo',
                data: codeData.userInfo
              })
              if (type==1){
                wx.reLaunch({
                  url: '/pages/index/index',
                })
              }
            }else{
              wx.showToast({
                title: '登录失败，请重新登录！',
                icon: 'none'
              })
              that.globalData.userInfo = "";
            }
            wx.hideLoading();
          },
          fail: function () {
            that.globalData.userInfo = "";
            wx.showToast({
              title: '登录失败，请重新登录！',
              icon: 'none'
            })
          }
        })
      },
      fail: function (err) {
        wx.hideLoading();
      }
    })
  },
  ajax: api.ajax,
  trim: api.trim,
  globalData: {
    settings: {
      language: null,
      employeeId: null
    },
    token: null,
    userInfo: null,
    commonUrl: "https://www.zhikelang.com/pet"
  }
})